import React, { useCallback, useContext, useState } from 'react';
import { IRoleManageTable, IRouleColumnsOpt } from '../type';
import cls from 'classnames';
import { RouleManageContext, switchRoleIsOpen } from '../hooks';
import { message, Table } from 'antd';
import {
  CaretDownOutlined,
  CaretRightOutlined,
} from '@ant-design/icons';
import { getResouColumns } from './PageConfig';
import { RoleAddEditModal } from './RoleAddEditModal';
// import { RoleAuthorizedModal } from './RoleAuthorizedModal';
import { useRequest, history } from 'umi';
import { RoleConfimStateModal } from './RoleConfimStateModal';
import { getKeyRouter } from '@/utils';
import { RoleDetailDrawer } from './RoleDetailDrawer';

export const RoleManageTable: React.FC<IRoleManageTable> = ({
  reloadRoleTable,
}) => {
  const {
    prefixCls,
    rouleDispatch,
    curRes,
    tableLoading,
    tableData,
    searchTableValue,
    expandedRowKeys,
    checkedRowKeys,
    reloadRoleTableState,
  } = useContext(RouleManageContext); //获取 上下文
  const [saveTableRow, setSaveTableRow] = useState<any>({}); //保存选中的 行数据
  const [addEditModalState, setAddEditModalState] = useState<boolean>(false); //是否打开新增编辑弹框
  const openShowModal = useCallback(
    (isModal: boolean, checkRows: any) => {
      setAddEditModalState(isModal);
      if (isModal) {
        setSaveTableRow(checkRows);
      }
    },
    [addEditModalState],
  );

  // const [showAuthorized, setShowAuthorized] = useState<boolean>(false); //授权弹框打开
  // const openAuthorModal = useCallback(
  //   (isModal: boolean, checkRows: any) => {
  //     setShowAuthorized(isModal);
  //     if (isModal) {
  //       setSaveTableRow(checkRows);
  //     }
  //   },
  //   [showAuthorized],
  // );

  const [showConfimModal, setShowConfimModal] = useState<boolean>(false); //禁用状态提示框
  const openConfimModal = useCallback(
    (isModal: boolean, checkRows: any) => {
      setShowConfimModal(isModal);
      if (isModal) {
        setSaveTableRow(checkRows);
      }
    },
    [showConfimModal],
  );

  // 是否打开详情抽屉
  const [showDetailDrawer, setShowDetailDrawer] = useState<boolean>(false);
  const showDetailCall = useCallback(
    (isShow: boolean) => {
      setShowDetailDrawer(isShow);
    },
    [showDetailDrawer],
  );

  // 表格操作方法
  const onPosOptClick: IRouleColumnsOpt = {
    openViewInfo: (record) => {
      setSaveTableRow(record);
      showDetailCall(true);
    },
    onEditAdd: (record) => {
      openShowModal(true, record);
    },
    grantOption: (record) => {
      history.push({
        pathname: `/roleController/grant/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          id: record?.id,
        },
      });
    },
    onChangeIsOpen: (checked, record) => {
      if (checked) {
        if (record?.pIsOpen == 0) {
          openConfimModal(true, record);
        } else {
          checkFalseIsOpen?.run(checked, record);
        }
      } else {
        openConfimModal(true, record);
      }
    },
  };

  let showColumns = getResouColumns(curRes, onPosOptClick, searchTableValue);

  // 修改下拉展开图标
  const expandIcon = (props: any) => {
    if (props.record.children && props.record.children.length > 0) {
      if (props.expanded) {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretDownOutlined />
            </span>
          </span>
        );
      } else {
        return (
          <span
            onClick={(e) => {
              props.onExpand(props.record, e);
            }}
            style={{
              float: 'left',
              marginRight: '5px',
            }}
          >
            <span style={{ fontSize: '10px' }}>
              <CaretRightOutlined />
            </span>
          </span>
        );
      }
    } else {
      return (
        <span
          style={{
            float: 'left',
            marginRight: '5px',
          }}
        >
          <span style={{ fontSize: '10px', visibility: 'hidden' }}>
            <CaretRightOutlined />
          </span>
        </span>
      );
    }
  };

  // 表格行点击选中改变方法
  const tableChange = (selectedRowKeys: any, selectedRows: any) => {
    rouleDispatch({
      type: 'role-checkedRowKeys',
      payload: selectedRowKeys,
    });
  };

  // 调用修改状态的按钮
  const checkFalseIsOpen = useRequest(
    (openState: boolean, recObj: any) => {
      let params = {
        versionNum: recObj?.versionNum,
        id: recObj?.id,
        isOpen: openState ? 1 : 0,
      };
      return switchRoleIsOpen(params);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message?.success(res?.msg);
          // reloadRoleTable()
          reloadRoleTableState();
        } else {
          message?.error(res?.msg);
        }
      },
    },
  );

  // 禁用资源
  const chanageSwitch = (check: boolean, resObj: any) => {
    checkFalseIsOpen?.run(check, resObj);
  };

  return (
    <>
      <div className={cls(prefixCls + 'table-content')}>
        <div className={cls('list-table')}>
          <Table
            size="small"
            columns={showColumns}
            bordered
            pagination={false}
            dataSource={tableData}
            loading={tableLoading || checkFalseIsOpen?.loading}
            rowKey={(record) => record?.id}
            scroll={{ x: 800, y: 'true' }}
            expandIcon={expandIcon}
            expandable={{
              onExpandedRowsChange: (keys: any) => {
                rouleDispatch({
                  type: 'role-expandedRowKeys',
                  payloadS: keys,
                });
              },
              expandedRowKeys: expandedRowKeys,
            }}
            rowSelection={{
              type: 'radio',
              selectedRowKeys: checkedRowKeys,
              onChange: tableChange,
              // getCheckboxProps: (record: any) => {
              //   if (record?.isOpen == 1) {
              //     return {
              //       disabled: false,
              //     };
              //   } else {
              //     return {
              //       disabled: true,
              //     };
              //   }
              // },
            }}
            onRow={(record) => {
              return {
                onClick: (event) => {
                  event.stopPropagation();
                  tableChange([record?.id], [record]);
                },
              };
            }}
          />
        </div>
      </div>

      {/* 编辑弹框 */}
      {addEditModalState && (
        <RoleAddEditModal
          visible={addEditModalState}
          onClose={() => {
            openShowModal(false, {});
          }}
          editAddRows={saveTableRow}
          tableReload={reloadRoleTable}
        />
      )}

      {/* 授权弹框 */}
      {/* {showAuthorized && (
        <RoleAuthorizedModal
          onClose={() => {
            openAuthorModal(false, {});
          }}
          tableRows={saveTableRow}
          visible={showAuthorized}
          reloadRoleTable={reloadRoleTable}
        />
      )} */}

      {/* 禁用提示弹框 */}
      {showConfimModal && (
        <RoleConfimStateModal
          visible={showConfimModal}
          onClose={() => {
            openConfimModal(false, {});
          }}
          chanageSwitch={chanageSwitch}
          tableRowObj={saveTableRow}
        />
      )}

      <RoleDetailDrawer
        onRowDetail={saveTableRow}
        visible={showDetailDrawer}
        onCloceDrawer={showDetailCall}
      />
    </>
  );
};
